package com.hunliji.monitor.web.strategy.interception.handler.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hunliji.common.exception.WarnException;
import com.hunliji.monitor.dao.utils.TemplateReplaceUtil;
import com.hunliji.monitor.manager.api.FeiShuManager;
import com.hunliji.monitor.manager.api.FeishuInterceptionManager;
import com.hunliji.monitor.manager.api.model.dto.FeiShuSendMsgDTO;
import com.hunliji.monitor.manager.api.model.param.FeiShuSendMsgManagerParam;
import com.hunliji.monitor.share.component.mq.rocket.RocketMqFacade;
import com.hunliji.monitor.share.component.mq.rocket.constants.RocketMqConstants;
import com.hunliji.monitor.share.enums.ReceiveIdTypeEnum;
import com.hunliji.monitor.share.enums.feishu.InterceptEventTypeEnum;
import com.hunliji.monitor.share.enums.feishu.WorkItemKeyTypeEnum;
import com.hunliji.monitor.web.config.FeishuIssuePushConfig;
import com.hunliji.monitor.web.facade.FeiShuFacade;
import com.hunliji.monitor.web.model.param.feishu.InterceptPluginContextParam;
import com.hunliji.monitor.web.strategy.interception.handler.AbstractFeishuInterceptionHandler;
import com.hunliji.monitor.web.strategy.interception.param.FeishuInterceptionContext;
import com.lark.project.service.field.model.FieldValuePair;
import com.lark.project.service.workitem.model.WorkItemInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class WorkItemUpdateStateHandler extends AbstractFeishuInterceptionHandler {

    @Resource
    private FeiShuManager feiShuManager;

    @Resource
    private FeishuInterceptionManager feishuInterceptionManager;

    @Resource
    private FeishuIssuePushConfig feishuIssuePushConfig;

    @Resource
    private RocketMqFacade rocketMqFacade;

    @Resource
    private FeiShuFacade feiShuFacade;

    @Override
    public InterceptEventTypeEnum getEventType() {
        return InterceptEventTypeEnum.UPDATE_STATE;
    }

    @Override
    public void process(FeishuInterceptionContext context) {
        if (context == null) {
            log.warn("缺失上下文");
            return;
        }
        InterceptPluginContextParam param = context.getParam();
        if (CollectionUtils.isEmpty(param.getWorkItemInfo())) {
            log.warn("无工作项信息");
            return;
        }
        if (!WorkItemKeyTypeEnum.ISSUE.getTypeKey().equals(param.getWorkItemTypeKey())) {
            // 只处理缺陷
            return;
        }
        try {
            // 延迟2s，飞书的数据可能有延迟，直接查会查不到
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            log.warn("sleep failed!", e);
            return;
        }

        String accessToken = getAccessToken();

        Long workItemId = param.getWorkItemInfo().get(0).getWorkItemId();
        WorkItemInfo workItemInfo = feishuInterceptionManager.getWorkItemInfo(accessToken, workItemId, param.getProjectKey(), param.getWorkItemTypeKey());
        if (workItemInfo == null) {
            throw new WarnException("未获取到对应工作项");
        }

        List<Long> issueViewIds = feishuInterceptionManager.viewWorkItemList(accessToken, param.getProjectKey(), feishuIssuePushConfig.getIssueViewId());
        if (issueViewIds.contains(workItemId) && ("RESOLVED".equals(workItemInfo.getSubStage()))) {
                JSONObject jsonObject = getUpdateMessageFromTemplate(workItemInfo.getName(), workItemInfo.getFields(),  workItemInfo.getSubStage(), workItemInfo.getID());
                FeiShuSendMsgManagerParam sendParam = FeiShuSendMsgManagerParam.builder()
                        .receiveIdType(ReceiveIdTypeEnum.CHAT_ID.getCode())
                        .receiveId(feishuIssuePushConfig.getChatId())
                        .content(jsonObject.toJSONString())
                        .msgType("interactive")
                        .build();
                FeiShuSendMsgDTO feiShuSendMsgDTO = feiShuManager.sendMsg(sendParam, feiShuFacade.getAccessToken());


                JSONObject delaySendResult = new JSONObject();
                delaySendResult.put("workItemId", workItemId);
                delaySendResult.put("type", getEventType().getEventType());
                delaySendResult.put("messageId", feiShuSendMsgDTO.getMessageId());
                delaySendResult.put("issueName", workItemInfo.getName());
                delaySendResult.put("projectKey", param.getProjectKey());
                delaySendResult.put("workItemTypeKey", workItemInfo.getWorkItemTypeKey());
                rocketMqFacade.delayedSend(RocketMqConstants.TOPIC_FEISHU_DELAY, RocketMqConstants.TAG_FEISHU_DELAY, delaySendResult.toJSONString(), RocketMqConstants.DelayLevel.TWO_HOUR);
        }

    }


    @SuppressWarnings("unchecked")
    private JSONObject getUpdateMessageFromTemplate(String content, List<FieldValuePair> fields, String status, Long id) {
        Map<String, Object> priorityMap = (Map<String, Object>) fields.stream()
                .filter(fieldValuePair -> fieldValuePair.getFieldKey().equals("priority"))
                .findFirst()
                .map(FieldValuePair::getFieldValue)
                .orElse(new HashMap<>());

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", content);
        resultMap.put("level", priorityMap.get("label").toString());
        resultMap.put("status", status);
        resultMap.put("userId", feishuIssuePushConfig.getUserOpenIds());
        resultMap.put("detailUrl", feishuIssuePushConfig.getDetailUrl() + id);
        resultMap.put("followUrl", getBeginUrl(feishuIssuePushConfig.getBeginUrl(), id, getEventType()));

        return JSON.parseObject(TemplateReplaceUtil.replace(feishuIssuePushConfig.getUpdateStateTemplate(), resultMap));
    }

    private String getBeginUrl(String beginUrl, Long id, InterceptEventTypeEnum eventType) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("workItemId", id);
        paramMap.put("type",eventType.getEventType());
        return TemplateReplaceUtil.replace(beginUrl, paramMap);
    }
}
